import './index.scss';
import initAbout from './js/about';
import initApply from './js/apply';
import initInfos from './js/infos';
import './js/contact';
import {
    throttle
} from './js/utils';

if (process.env.NODE_ENV !== 'production') {
    setTimeout(init, 1000);
} else {
    init();
}

const $sections = $('body > section');
const $navs = $('.site-header li a');

document.addEventListener("DOMContentLoaded", () => {
    setTimeout(() => {
        const h = window.innerHeight;
        window.scrollTo(0, 0);
    }, 200)
});

function init() {
    const handleScroll = throttle(scrollAndChangeNav, 500);
    window.addEventListener('scroll', handleScroll);

    const homeSwiper = new Swiper('#swiper-home', {
        direction: 'horizontal',
        loop: true,
        autoplay: {
            delay: 3000
        },
        pagination: {
            el: '.swiper-pagination',
            type: 'custom',
            renderCustom: (swiper, current, total) => {
                let html = [];
                for (let i = 1; i <= total; i++) {
                    html.push(
                        `<div class="pagination-item${current === i ? ' active' : ''
                        }"></div>`
                    );
                }
                return html.join('');
            }
        }
    });

    initAbout();

    const strategySwiperNavs = ['投资理念', '投资领域'];
    const strategySwiper = new Swiper('#swiper-strategy', {
        loop: true,
        simulateTouch: false,
        centeredSlides: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
            renderBullet: (current, className) => {
                return `<span class="${className}">${strategySwiperNavs[current]
                    }</span>`;
            }
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev'
        }
    });

    const applyStepSwiperNavs = ['直投项目合作流程', '子基金合作流程'];
    const applyStepSwiper = new Swiper('#swiper-apply-step', {
        loop: true,
        simulateTouch: false,
        centeredSlides: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
            renderBullet: (current, className) => {
                return `<span class="${className}">${applyStepSwiperNavs[current]
                    }</span>`;
            }
        },

    });

    initApply();

    initInfos();
}

function scrollAndChangeNav() {
    const scrollY = window.scrollY;
    let found = false;
    let i = 0;
    const len = $sections.length;
    while (i < len && !found) {
        const pos = $sections.eq(i).offset().top;
        if (pos > scrollY) {
            found = true;
            break;
        }
        i++;
    }

    const anchor = $sections.eq(i - 1).attr('id');
    $navs
        .removeClass('active')
        .filter(`[href$=${anchor}]`)
        .addClass('active');
}